<template>
  <view class="history-container">
    <!-- 标题区域 -->
    <view class="header">
      <text class="title">历史表扬榜</text>
      <text class="subtitle">{{studentName}}的优秀表现记录</text>
    </view>

    <!-- 日期选择卡片 -->
    <scroll-view scroll-x class="date-scroll" :scroll-into-view="'date-'+activeDateIndex">
      <view class="date-cards">
        <view v-for="(date, index) in dateList" :key="index" :id="'date-'+index" class="date-card"
          :class="{active: activeDateIndex === index}" @click="changeDate(index)"
          :animation="dateCardAnim[index]">
          <text class="day">{{ formatDay(date) }}</text>
          <text class="weekday">{{ formatWeekday(date) }}</text>
          <text class="date">{{ formatDate(date) }}</text>
        </view>
      </view>
    </scroll-view>

    <!-- 表扬统计卡片 -->
    <view class="stats-container">
      <view class="glass-card stats-card" :animation="statsAnim">
        <view class="stat-item">
          <text class="stat-value">{{dailyPraiseCount}}</text>
          <text class="stat-label">今日表扬</text>
        </view>
        <view class="stat-item">
          <text class="stat-value">{{subjectCount}}</text>
          <text class="stat-label">涉及科目</text>
        </view>
        <view class="stat-item">
          <text class="stat-value">{{teacherCount}}</text>
          <text class="stat-label">表扬老师</text>
        </view>
      </view>
    </view>

    <!-- 表扬记录列表 -->
    <view class="praise-list">
      <view class="praise-item-container" v-for="(item, index) in filteredPraises" :key="item.id">
        <!-- 删除按钮 -->
        <view class="delete-btn" v-if="teacherSubjects.includes(item.subject)" @click="deletePraise(item.id)">
          <uni-icons type="trash" size="24" color="#fff"></uni-icons>
        </view>

        <!-- 表扬卡片 -->
        <view class="glass-card praise-item" :animation="itemAnim[index]"
          @touchstart="touchStart($event, item.id)" @touchmove="touchMove($event, item.id)"
          @touchend="touchEnd(item.id)" :style="{transform: `translateX(${item.translateX || 0}px)`}">
          <view class="subject-icon" :style="{backgroundColor: getSubjectColor(item.subject)}">
            <text>{{getSubjectAbbr(item.subject)}}</text>
          </view>
          <view class="praise-content">
            <view class="praise-header">
              <text class="subject-detail">{{ item.subjectDetail }}</text>
              <text class="teacher-name">{{ item.teacherName }}</text>
            </view>
            <view class="praise-body">
              <text class="praise-text">{{ item.marks || '表现优秀，继续努力！' }}</text>
            </view>
            <view class="praise-footer">
              <text class="time">{{ formatTime(item.createTime) }}</text>
              <text class="subject">{{ item.subject }}</text>
            </view>
          </view>
        </view>
      </view>

      <view class="empty-tip" v-if="filteredPraises.length === 0">
        <image src="/static/images/empty.png" mode="aspectFit"></image>
        <text>这一天没有表扬记录哦~</text>
      </view>
    </view>
  </view>
</template>

<script>
  import {
    globalVariable
  } from '../../configMy.js';
  export default {
    data() {
      return {
        teacher: {},
        studentName: '',
        teacherSubjects: [],
        activeDateIndex: 0,
        dateList: [],
        praiseList: [],
        dateCardAnim: [],
        itemAnim: [],
        statsAnim: {},
        touchStartX: 0,
        currentTranslateX: 0,
        activeIndex: -1,
        touchStates: {},
        activeSwipeId: null,
        studentId: 0
      }
    },
    computed: {
      filteredPraises() {
        if (this.dateList.length === 0) return [];
        const selectedDate = this.dateList[this.activeDateIndex];
        
        return this.praiseList.filter(item => {
          const itemDate = item.createTime.split(' ')[0];
          return itemDate === selectedDate;
        }).sort((a, b) => {
          return new Date(b.createTime) - new Date(a.createTime);
        }).map(item => {
          return {
            ...item,
            translateX: item.translateX || 0
          }
        });
      },
      dailyPraiseCount() {
        return this.filteredPraises.length;
      },
      subjectCount() {
        const subjects = new Set(this.filteredPraises.map(item => item.subject).filter(Boolean));
        return subjects.size;
      },
      teacherCount() {
        const teachers = new Set(this.filteredPraises.map(item => item.teacherName).filter(Boolean));
        return teachers.size;
      }
    },
    onLoad(options) {
      this.studentId = options.studentId || 6;
	  this.grade=options.grade
      let that = this;
      uni.getStorage({
        key: 'teacher',
        success(res) {
          that.teacher = res.data;
          that.fetchStudentPraises();
          that.fetchTeacherSubjects();
        }
      })
    },
    methods: {
      fetchStudentPraises() {
        uni.showLoading({
          title: '加载中...'
        });
        
        uni.request({
          url: `${globalVariable}/getPriseByStudentId?studentId=${this.studentId}`,
          success: (res) => {
            uni.hideLoading();
            let info = res.data;
            if (info.status == 1) {
              this.praiseList = info.data;
              if (this.praiseList.length > 0) {
                this.studentName = this.praiseList[0].studentName;
              }
              this.initDates();
              this.initAnimations();
            } else {
              uni.showToast({
                title: info.message || '暂无数据',
                icon: 'none'
              });
            }
          },
          fail: (err) => {
            uni.hideLoading();
            uni.showToast({
              title: '加载失败',
              icon: 'none'
            });
            console.error('请求失败:', err);
          }
        });
      },
      fetchTeacherSubjects() {
        uni.request({
          url: `${globalVariable}/getTeacherSubject?teacherId=${this.teacher.teacherId}&grade=`+this.grade,
          success: (res) => {
            if (res.data.status === 1) {
              this.teacherSubjects = res.data.data.map(item => item.subject);
            }
          }
        })
      },
      getSubjectColor(subject) {
        if (!subject) return '#9E9E9E';
        const colors = {
          '语文': '#FF9A9E',
          '数学': '#667EEA',
          '英语': '#FAC858',
          '物理': '#91CB74',
          '化学': '#FF8C66',
          '生物': '#37BC9B',
          '地理': '#5D9CEC',
          '历史': '#DA4453',
          '政治': '#967ADC'
        };
        return colors[subject] || '#607D8B';
      },
      getSubjectAbbr(subject) {
        if (!subject) return '表';
        return subject.substring(0, 1);
      },
      touchStart(e, id) {
        const item = this.praiseList.find(item => item.id === id);
        if (!this.teacherSubjects.includes(item.subject)) return;
        if (this.activeSwipeId && this.activeSwipeId !== id) {
          this.$set(this.praiseList.find(item => item.id === this.activeSwipeId), 'translateX', 0);
        }

        this.activeSwipeId = id;
        this.touchStates[id] = {
          startX: e.touches[0].clientX,
          startTime: Date.now()
        };
      },
      touchMove(e, id) {
        const item = this.praiseList.find(item => item.id === id);
        if (!this.teacherSubjects.includes(item.subject)) return;
        if (this.activeSwipeId !== id) return;

        const touchX = e.touches[0].clientX;
        const diffX = touchX - this.touchStates[id].startX;

        if (diffX > 0) {
          this.$set(this.praiseList.find(item => item.id === id), 'translateX', 0);
          return;
        }

        const maxLeft = -100;
        this.$set(this.praiseList.find(item => item.id === id), 'translateX', Math.max(diffX, maxLeft));
      },
      touchEnd(id) {
        const item = this.praiseList.find(item => item.id === id);
        if (!this.teacherSubjects.includes(item.subject)) return;
        if (this.activeSwipeId !== id) return;

        const currentX = this.praiseList.find(item => item.id === id).translateX;
        const threshold = -50;
        const velocity = Math.abs(currentX) / (Date.now() - this.touchStates[id].startTime);

        if (currentX <= threshold || velocity > 0.3) {
          this.$set(this.praiseList.find(item => item.id === id), 'translateX', -80);
        } else {
          this.$set(this.praiseList.find(item => item.id === id), 'translateX', 0);
          this.activeSwipeId = null;
        }

        delete this.touchStates[id];
      },
      deletePraise(id) {
        uni.showModal({
          title: '提示',
          content: '确定要删除这条表扬记录吗？',
          success: (res) => {
            if (res.confirm) {
              const url = `${globalVariable}/deleteParise?id=${id}`;
              
              uni.request({
                url: url,
                method: 'POST',
                success: (res) => {
                  let info = res.data;
                  if(info.status == 1) {
                    this.praiseList = this.praiseList.filter(item => item.id !== id);
                    
                    uni.showToast({
                      title: '删除成功',
                      icon: 'success'
                    });
                    
                    this.activeSwipeId = null;
                  } else {
                    uni.showToast({
                      title: info.message || '删除失败',
                      icon: 'none'
                    });
                  }
                },
                fail: (err) => {
                  uni.showToast({
                    title: '网络错误，删除失败',
                    icon: 'none'
                  });
                  console.error('删除请求失败:', err);
                }
              });
            } else {
              this.$set(this.praiseList.find(item => item.id === id), 'translateX', 0);
              this.activeSwipeId = null;
            }
          }
        });
      },
      initDates() {
        const dates = this.praiseList.map(item => item.createTime.split(' ')[0]);
        const uniqueDates = [...new Set(dates)].sort((a, b) => new Date(b) - new Date(a));
        this.dateList = uniqueDates.slice(0, 30);

        if (this.dateList.length === 0) {
          const today = new Date();
          for (let i = 0; i < 7; i++) {
            const date = new Date();
            date.setDate(today.getDate() - i);
            const dateStr = `${date.getFullYear()}-${(date.getMonth()+1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`;
            this.dateList.push(dateStr);
          }
        }
      },
      initAnimations() {
        // 日期卡片动画
        this.dateCardAnim = this.dateList.map((_, index) => {
          return uni.createAnimation({
            duration: 600,
            delay: index * 100,
            timingFunction: 'ease-out'
          }).opacity(0).translateX(30).step().export();
        });

        // 列表项动画
        this.itemAnim = this.praiseList.map((_, index) => {
          return uni.createAnimation({
            duration: 600,
            delay: index * 50,
            timingFunction: 'ease-out'
          }).opacity(0).translateY(20).step().export();
        });

        // 统计卡片动画
        this.statsAnim = uni.createAnimation({
          duration: 800,
          timingFunction: 'ease-out'
        }).opacity(0).scale(0.9).step().export();

        // 执行动画
        setTimeout(() => {
          this.dateCardAnim = this.dateList.map(() => {
            return uni.createAnimation({
              duration: 600,
              timingFunction: 'ease-out'
            }).opacity(1).translateX(0).step().export();
          });

          this.itemAnim = this.praiseList.map(() => {
            return uni.createAnimation({
              duration: 600,
              timingFunction: 'ease-out'
            }).opacity(1).translateY(0).step().export();
          });

          this.statsAnim = uni.createAnimation({
            duration: 800,
            timingFunction: 'ease-out'
          }).opacity(1).scale(1).step().export();
        }, 300);
      },
      changeDate(index) {
        this.activeDateIndex = index;

        this.dateCardAnim = this.dateCardAnim.map((_, i) => {
          const anim = uni.createAnimation({
            duration: 300,
            timingFunction: 'ease-out'
          });

          if (i === index) {
            anim.scale(0.95).step({
              duration: 100
            });
            anim.scale(1).step({
              duration: 200
            });
          }

          return anim.export();
        });
      },
      formatDay(date) {
        if (!date) return '';
        const d = new Date(date.replace(/-/g, '/'));
        return d.getDate();
      },
      formatWeekday(date) {
        if (!date) return '';
        const weekdays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
        const d = new Date(date.replace(/-/g, '/'));
        return weekdays[d.getDay()];
      },
      formatDate(date) {
        if (!date) return '';
        const d = new Date(date.replace(/-/g, '/'));
        return `${d.getMonth() + 1}月${d.getDate()}日`;
      },
      formatTime(time) {
        if (!time) return '';
        return time.split(' ')[1].substring(0, 5);
      }
    }
  }
</script>

<style lang="scss" scoped>
  .praise-item-container {
    position: relative;
    margin-bottom: 20rpx;
    overflow: hidden;
    border-radius: 24rpx;
  }

  .delete-btn {
    position: absolute;
    right: 0;
    top: 0;
    bottom: 0;
    width: 80px;
    background-color: #ff5a5f;
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 1;
  }

  .praise-item {
    position: relative;
    z-index: 2;
    transition: transform 0.3s ease;
  }

  .history-container {
    padding: 30rpx;
    min-height: 100vh;
    background: linear-gradient(135deg, #f5f7fa 0%, #e4e8f0 100%);
    background-image:
      radial-gradient(circle at 10% 20%, rgba(255, 15, 51, 0.05) 0%, transparent 20%),
      radial-gradient(circle at 90% 80%, rgba(8, 255, 111, 0.05) 0%, transparent 20%);

    .header {
      margin-bottom: 40rpx;
      text-align: center;

      .title {
        display: block;
        font-size: 48rpx;
        font-weight: bold;
        color: #333;
        margin-bottom: 10rpx;
        background: linear-gradient(to right, #667eea, #764ba2);
        -webkit-background-clip: text;
        -webkit-text-fill-color: transparent;
      }

      .subtitle {
        display: block;
        font-size: 28rpx;
        color: #888;
      }
    }

    /* 日期选择区域 */
    .date-scroll {
      white-space: nowrap;
      margin-bottom: 30rpx;
      padding: 10rpx 0;

      .date-cards {
        display: inline-flex;
        padding: 0 20rpx;
      }

      .date-card {
        display: inline-flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        width: 120rpx;
        height: 150rpx;
        margin-right: 20rpx;
        border-radius: 20rpx;
        background: rgba(255, 255, 255, 0.6);
        backdrop-filter: blur(10px);
        -webkit-backdrop-filter: blur(10px);
        box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.05);
        transition: all 0.3s ease;

        &.active {
          background: rgba(102, 126, 234, 0.2);
          box-shadow: 0 8rpx 24rpx rgba(102, 126, 234, 0.2);

          .day {
            color: #667EEA;
            font-weight: bold;
          }

          .weekday,
          .date {
            color: #667EEA;
          }
        }

        .day {
          font-size: 48rpx;
          font-weight: bold;
          color: #333;
          margin-bottom: 6rpx;
          transition: all 0.3s ease;
        }

        .weekday {
          font-size: 24rpx;
          color: #999;
          margin-bottom: 4rpx;
          transition: all 0.3s ease;
        }

        .date {
          font-size: 22rpx;
          color: #999;
          transition: all 0.3s ease;
        }
      }
    }

    /* 统计卡片 */
    .stats-container {
      margin-bottom: 30rpx;
      
      .stats-card {
        display: flex;
        justify-content: space-around;
        padding: 30rpx;
        margin-bottom: 30rpx;
        
        .stat-item {
          display: flex;
          flex-direction: column;
          align-items: center;
          
          .stat-value {
            font-size: 40rpx;
            font-weight: bold;
            color: #667EEA;
            margin-bottom: 10rpx;
          }
          
          .stat-label {
            font-size: 24rpx;
            color: #666;
          }
        }
      }
    }

    /* 表扬列表 */
    .praise-list {
      .praise-item {
        display: flex;
        padding: 30rpx;
        transition: all 0.3s ease;

        &:active {
          transform: scale(0.98);
        }

        .subject-icon {
          width: 80rpx;
          height: 80rpx;
          border-radius: 50%;
          display: flex;
          align-items: center;
          justify-content: center;
          color: white;
          font-size: 36rpx;
          font-weight: bold;
          margin-right: 20rpx;
          flex-shrink: 0;
        }

        .praise-content {
          flex: 1;

          .praise-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 15rpx;

            .subject-detail {
              font-size: 30rpx;
              font-weight: bold;
              color: #333;
              flex: 1;
              margin-right: 20rpx;
            }

            .teacher-name {
              font-size: 26rpx;
              color: #666;
            }
          }

          .praise-body {
            margin-bottom: 15rpx;
            
            .praise-text {
              font-size: 28rpx;
              color: #666;
              line-height: 1.5;
            }
          }

          .praise-footer {
            display: flex;
            justify-content: space-between;
            align-items: center;

            .time {
              font-size: 24rpx;
              color: #999;
            }

            .subject {
              font-size: 24rpx;
              color: #666;
              background: rgba(0, 0, 0, 0.05);
              padding: 4rpx 12rpx;
              border-radius: 20rpx;
            }
          }
        }
      }

      .empty-tip {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        padding: 60rpx 0;
        text-align: center;

        image {
          width: 200rpx;
          height: 200rpx;
          margin-bottom: 20rpx;
          opacity: 0.6;
        }

        text {
          font-size: 28rpx;
          color: #999;
        }
      }
    }
  }

  /* 毛玻璃效果 */
  .glass-card {
    background: rgba(255, 255, 255, 0.7);
    backdrop-filter: blur(20px);
    -webkit-backdrop-filter: blur(20px);
    border-radius: 24rpx;
    box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.08);
    border: 1px solid rgba(255, 255, 255, 0.4);
    transition: all 0.3s ease;
    
    &:hover {
      box-shadow: 0 12rpx 30rpx rgba(0, 0, 0, 0.12);
    }
  }
</style>